package com.hse.virtualnetwork;

import com.hse.network.ICoordinator;
import com.hse.network.ICoordinatorClient;
import com.hse.network.exceptions.NetworkException;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * Created by IntelliJ IDEA.
 * User: Lexa
 * Date: May 31, 2009
 * Time: 6:42:15 PM
 * To change this template use File | Settings | File Templates.
 */
public class VirtualCoordinator implements ICoordinator {
    private final static Short PORT_NUMBER = 8789;
    private final ServerSocketChannel sock;
    private Socket clientSocket;

    public VirtualCoordinator() throws InstantiationException {
        try {
            sock = ServerSocketChannel.open();
        } catch (IOException e) {
            throw new InstantiationException();
        }
    }

    public void createNetwork(Short panId) throws NetworkException {
        try {
            sock.socket().bind(new InetSocketAddress(PORT_NUMBER));
        } catch (IOException e) {
            throw new NetworkException(e);
        }
    }

    public boolean canAccept() throws NetworkException {
        try {
            sock.configureBlocking(false);
            SocketChannel clientSocketChannel = sock.accept();
            sock.configureBlocking(true);

            clientSocket = clientSocketChannel == null ? null : clientSocketChannel.socket();
            return clientSocketChannel != null;
        } catch (IOException e) {
            throw new NetworkException(e);
        }
    }

    public ICoordinatorClient accept() throws NetworkException {
        final Socket client;
        if (clientSocket != null) {
            client = clientSocket;
        } else {
            try {
                final SocketChannel socketChannel = sock.accept();
                client = socketChannel.socket();
            } catch (IOException e) {
                throw new NetworkException(e);
            }
        }
        clientSocket = null;

        try {
            return new VirtualCoordinatorClient(client);
        } catch (SocketException e) {
            throw new NetworkException(e);
        }
    }

    public void destroyNetwork() throws NetworkException {
        close();
    }

    public void close() {
        try {
            sock.close();
        } catch (IOException e) {
        }
    }
}
